<template>
  <el-container>
    <div class="chat-main" ref="ChatMessage">
      <div class="chat-messages">
        <el-scrollbar wrap-class="message-list">
          <div v-for="message in messages" :key="message.id" class="message-wrapper">
            <div :class="{
              'client-message': message.sender === 'client',
              'merchant-message': message.sender === 'merchant',
            }">
              <!--      头像判断      -->
              <div class="user-avatar" v-if="message.sender === 'merchant'">
                <svg t="1702006258443" class="icon" viewBox="0 0 1024 1024" version="1.1"
                  xmlns="http://www.w3.org/2000/svg" p-id="898" width="26" height="26">
                  <path
                    d="M222.9248 222.208h574.464c24.1664 0 43.7248-19.5584 43.7248-43.7248 0-24.1664-19.5584-43.7248-43.7248-43.7248H222.9248c-24.1664 0-43.7248 19.5584-43.7248 43.7248-0.0512 24.1664 19.5584 43.7248 43.7248 43.7248z"
                    fill="#757BF2" p-id="899"></path>
                  <path
                    d="M918.784 421.12l-70.2976-153.5488a2.1504 2.1504 0 0 0-1.8944-1.2288H180.5312c-0.8192 0-1.5872 0.512-1.8944 1.2288L111.6672 422.5024c-12.2368 28.2624-10.3424 61.1328 6.656 86.784 19.5584 29.4912 53.0944 48.9472 91.136 48.9472 44.9536 0 83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.296 66.048 100.2496 66.048s83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.2448 66.048 100.2496 66.048s83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.296 66.048 100.2496 66.048 35.6864 0 67.3792-17.1008 87.296-43.5712 20.1728-26.8288 23.1424-62.976 9.1648-93.5424zM720.128 575.9488c-28.3648 22.8864-64.1536 36.0448-102.144 36.0448s-73.7792-13.1584-102.144-36.0448a162.42176 162.42176 0 0 1-102.144 36.0448c-37.9904 0-73.7792-13.1584-102.144-36.0448a162.42176 162.42176 0 0 1-102.144 36.0448c-10.24 0-20.3776-0.9728-30.2592-2.816v222.3104c0 31.8976 25.856 57.7536 57.7536 57.7536H786.944c31.8976 0 57.7536-25.856 57.7536-57.7536v-221.184c-7.424 1.024-14.8992 1.6384-22.4256 1.6384-37.9904 0.0512-73.7792-13.1584-102.144-35.9936z"
                    fill="#6C6CEA" p-id="900"></path>
                  <path
                    d="M846.592 266.3424H180.5312c-0.8192 0-1.5872 0.512-1.8944 1.2288L111.6672 422.5024c-12.2368 28.2624-10.3424 61.1328 6.656 86.784 19.5584 29.4912 53.0944 48.9472 91.136 48.9472 44.9536 0 83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.296 66.048 100.2496 66.048s83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.2448 66.048 100.2496 66.048 44.9536 0 83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c14.8992 34.5088 46.9504 59.8016 85.4528 65.024 36.0448-76.544 56.2688-161.9968 56.2688-252.2112 0-1.3824-0.0512-2.816-0.0512-4.1984l-15.2064-33.1776a2.24768 2.24768 0 0 0-1.9456-1.28zM720.128 575.9488c-28.3648 22.8864-64.1536 36.0448-102.144 36.0448s-73.7792-13.1584-102.144-36.0448a162.42176 162.42176 0 0 1-102.144 36.0448c-37.9904 0-73.7792-13.1584-102.144-36.0448a162.42176 162.42176 0 0 1-102.144 36.0448c-10.24 0-20.3776-0.9728-30.2592-2.816v222.3104c0 31.8976 25.856 57.7536 57.7536 57.7536h133.0176c175.0528-29.3888 324.0448-135.4752 411.2384-282.5216-22.3744-5.888-43.1616-16.384-61.0304-30.7712z"
                    fill="#757BF2" p-id="901"></path>
                  <path
                    d="M700.2624 134.7584H222.9248c-24.1664 0-43.7248 19.5584-43.7248 43.7248 0 24.1664 19.5584 43.7248 43.7248 43.7248h464.896a592.5888 592.5888 0 0 0 12.4416-87.4496zM676.3008 266.3424H180.5312c-0.8192 0-1.5872 0.512-1.8944 1.2288L111.6672 422.5024c-12.2368 28.2624-10.3424 61.1328 6.656 86.784 19.5584 29.4912 53.0944 48.9472 91.136 48.9472 44.9536 0 83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.296 66.048 100.2496 66.048s83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c3.072 7.168 6.9632 13.9264 11.4176 20.224 67.4816-67.8912 118.6304-152.0128 147.0976-246.0672zM399.1552 611.2768a162.48832 162.48832 0 0 1-87.552-35.3792 162.42176 162.42176 0 0 1-102.144 36.0448c-10.24 0-20.3776-0.9728-30.2592-2.816v73.7792c79.104-9.3184 153.4976-34.2528 219.9552-71.6288z"
                    fill="#8486F8" p-id="902"></path>
                  <path
                    d="M497.408 134.7584H222.9248c-24.1664 0-43.7248 19.5584-43.7248 43.7248 0 24.1664 19.5584 43.7248 43.7248 43.7248h224.3072c19.0976-27.5456 35.8912-56.7808 50.176-87.4496zM413.3888 266.3424H180.5312c-0.8192 0-1.5872 0.512-1.8944 1.2288L111.6672 422.5024c-5.1712 11.8784-7.6288 24.6272-7.68 37.2736 122.7264-30.6688 230.3488-99.584 309.4016-193.4336z"
                    fill="#8D92F8" p-id="903"></path>
                </svg>
              </div>
              <template v-if="message.sender === 'client'">
                <img src="@/assets/images/avatar.jpg" alt="Avatar" class="user-avatar" />
              </template>
              <div class="message-content">
                <div class="message-timestamp">{{ message.createTime }}</div>
                {{ message.content }}
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <el-footer height="90px">
      <el-input type="textarea" :rows="4" placeholder="请输入内容" resize="none" height="80px" weith="10px" v-model="textarea">
      </el-input>
      <div class="button">
        <el-button @click="closeItem()">关 闭</el-button>
        <el-button @click="sendMessage" type="primary" :disabled="sendBtnDisable">发 送</el-button>
      </div>
    </el-footer>
  </el-container>
</template>

<script>
import service from "@/api/saleManagement/message/index.js";
import { getEvaluationData } from "@/api/client";
import axios from "axios";
export default {
  name: "ChatInterface",
  props: {
    carId: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      //发送消息
      textarea: "",
      //消息
      messages: [],
      // 过滤后的文本内容
      filteredContent: "",
      //敏感词库
      sensitiveWords: [],
      // 当前页面请求响应的消息个数是否有100
      msgHas100: false,
      //分页位置
      pageNum: -1,
      sendBtnDisable: false,
    };
  },

  mounted() {
    document
      .querySelector(".chat-messages")
      .addEventListener("scroll", this.handleScroll);
  },
  beforeDestroy() {
    document
      .querySelector(".chat-messages")
      .removeEventListener("scroll", this.handleScroll, false);
    document.removeEventListener(
      "visibilitychange",
      this.handleVisibilityChange
    );
  },
  async created() {
    this.sensitiveWords = this.$store.getters.sensitiveWords || [];
    if (this.sensitiveWords) {
      // 加载敏感词
      await this.loadSensitiveWords();
    }
    await this.init();
    document.addEventListener("visibilitychange", this.handleVisibilityChange);
    this.$nextTick(() => {
      // dom 元素更新后执行滚动条到底部 否则不生效
      let scrollElem = this.$refs.ChatMessage;
      scrollElem.scrollTop = scrollElem.scrollHeight;
    });
  },
  methods: {
    /**
     * 发送消息
     * @returns {Promise<void>}
     */
    async sendMessage() {
      this.sendBtnDisable = true;
      if (!this.textarea || this.textarea.trim().length === 0) {
        this.$modal.msgWarning("不能发送空文本");
        this.sendBtnDisable = false;
        return;
      }
      // 处理发送消息的逻辑，可以将新消息添加到messages数组中
      await this.filterContent();
      const newMessage = {
        //客服
        sender: "merchant",
        content: this.filteredContent,
      };
      //将消息发送给后台存储
      await service.reply(this.carId, newMessage);

      if (this.messages.length > 100) {
        //pageNum置为-1
        this.pageNum = -1;
        this.messages = [];
      }
      //重新获取页面数据
      await this.init();
      //滚动到底部
      this.scrollToBottom();
      this.textarea = ""; // 清空输入框
      this.sendBtnDisable = false;
    },
    //加载聊天信息
    async init() {
      await getEvaluationData(this.carId, this.pageNum).then((resp) => {
        if (this.pageNum === -1) {
          this.messages = resp.data || [];
        } else {
          this.messages = (resp.data || []).concat(this.messages);
        }
        this.msgHas100 = 100 === (resp.data || []).length;
        this.loading = false;
      });
    },
    closeItem() {
      this.$emit("transfer", false);
    },
    //加載敏感詞
    async loadSensitiveWords() {
      try {
        const files = [
          "广告.txt",
          "色情类.txt",
          "涉枪涉爆违法信息关键词.txt",
          "网址.txt",
          "政治类.txt",
        ];
        const sensitiveWords = [];

        // 遍历读取每个敏感词文件
        for (const file of files) {
          const response = await axios.get(`/sensitive_words/${file}`);
          const words = response.data
            .split("\n")
            .map((word) => word.trim())
            .filter((word) => word !== "");
          sensitiveWords.push(...words);
        }
        //将敏感词存储到vuex中
        await this.$store.commit("sensitiveWords/LOAD_DATA", sensitiveWords);
        this.sensitiveWords = sensitiveWords;
      } catch (error) {
        console.error("Failed to load sensitive words", error);
      }
    },
    filterContent() {
      // 过滤敏感词
      let filteredContent = this.textarea;
      this.sensitiveWords.forEach((word) => {
        const regExp = new RegExp(word, "gi");
        filteredContent = filteredContent.replace(
          regExp,
          "*".repeat(word.length)
        );
      });

      // 更新过滤后的文本内容
      this.filteredContent = filteredContent;
    },
    // 鼠标滚动事件
    handleScroll() {
      // 变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop = document.querySelector(".chat-messages").scrollTop;
      // 滚动条到顶部的条件
      // loading防止事件重复触发
      if (!this.loading && scrollTop < 50) {
        this.loading = true;
        if (this.loading) {
          if (this.msgHas100) {
            this.pageNum -= 100; // 页数+1
            // 重新加载数剧
            this.init();
          }
        }
      }
    },
    //移动到页面底部
    async scrollToBottom() {
      // this.$nextTick 将回调延迟到下次DOM更新循环之后执行。在修改数据之后立即使用它，然后等待DOM更新
      this.$nextTick(() => {
        // dom 元素更新后执行滚动条到底部 否则不生效
        let scrollElem = this.$refs.ChatMessage;
        // scrollElem.scrollTop = scrollElem.scrollHeight
        scrollElem.scrollTo({
          top: scrollElem.scrollHeight,
          behavior: "smooth",
        });
      });
    },
    /**
     * 判断用户视角是否已离开当前页面
     */
    async handleVisibilityChange() {
      if (document.visibilityState === "hidden") {
        // 用户离开当前页面的逻辑;
      } else {
        // 用户返回当前页面的逻辑
        await this.init();
      }
      this.$nextTick(() => {
        // dom 元素更新后执行滚动条到底部 否则不生效
        let scrollElem = this.$refs.ChatMessage;
        scrollElem.scrollTop = scrollElem.scrollHeight;
      });
    },
  },
};
</script>

<style scoped lang="scss">
.el-footer {
  color: #333;
  text-align: center;
  line-height: 80px;
}

.el-header span {
  text-align: center;
}

.chat-main {
  color: #333;
  height: 500px;
  overflow: auto;
}

.button {
  position: absolute;
  right: 50px;
  bottom: 10px;
}

/* 消息设置 */
.chat-messages {
  margin-top: 5px;
  flex: 1;
  overflow-y: auto;
}

.message-list {
  padding: 10px;
}

.message-wrapper {
  margin-bottom: 10px;
}

.user-avatar {
  max-width: 40px;
  /* 设置最大宽度 */
  max-height: 40px;
  /* 设置最大高度 */
  border-radius: 50%;
  /* 使头像呈现圆形，根据需要调整 */
}

.merchant-message {
  display: flex;
  flex-direction: row-reverse;
  /* 将消息和头像的顺序反转，消息在右侧，头像在左侧 */
  align-items: center;
}

.client-message {
  display: flex;
  flex-direction: row;
  /* 消息在左侧，头像在右侧 */
  align-items: center;
}

.message-content {
  display: block;
  background-color: #e6f7ff;
  /* client消息背景色 */
  border-radius: 8px;
  padding: 8px;
  max-width: 70%;
}

.message-timestamp {
  height: 20px;
  color: #999;
  font-size: 12px;
}

.chat-input {
  display: flex;
  align-items: center;
  padding: 10px;
}

.input-message {
  flex: 1;
  margin-right: 10px;
}
</style>
